#include "../Base/stdafx.h"
#include "MeshHelper.h"


void MeshHelper::CalculateTangent( Vertex& p1, Vertex& p2, Vertex& p3 )
{
	D3DXVECTOR3 v1 = p1.m_Pos, v2 = p2.m_Pos, v3 = p3.m_Pos;
	D3DXVECTOR3 w1 = p1.m_Tex, w2 = p2.m_Tex, w3 = p3.m_Tex;
	D3DXVECTOR3 n1 = p1.m_Norm, n2 = p2.m_Norm, n3 = p3.m_Norm;

	float x1 = v2.x - v1.x;
	float x2 = v3.x - v1.x;
	float y1 = v2.y - v1.y;
	float y2 = v3.y - v1.y;
	float z1 = v2.z - v1.z;
	float z2 = v3.z - v1.z;

	float s1 = w2.x - w1.x;
	float s2 = w3.x - w1.x;
	float t1 = w2.y - w1.y;
	float t2 = w3.y - w1.y;

	float r = 1.0f / (s1 * t2 - s2 * t1);

	D3DXVECTOR3 tan1((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r );
	D3DXVECTOR3 tan2((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r );

	D3DXVECTOR3 tangent1;
	float n1tan1dot = D3DXVec3Dot(&n1, &tan1);
	tangent1 = n1 * n1tan1dot;
	tangent1  = tan1 - tangent1;
	D3DXVec3Normalize(&tangent1, &tangent1);

	D3DXVECTOR3 tangent2;
	tangent2 = n1 * n1tan1dot;
	tangent2 = tan1 - tangent1;
	D3DXVec3Normalize(&tangent2, &tangent2);

	D3DXVECTOR3 tangent3;
	tangent3 = n1 * n1tan1dot;
	tangent3 = tan1 - tangent1;
	D3DXVec3Normalize(&tangent3, &tangent3);

	p1.m_Tan = tangent1;
	p2.m_Tan = tangent2;
	p3.m_Tan = tangent3;
}